<?php
/**
 * 
 * @author Freezy
 *
 */
class Perbuatan extends MY_Controller {

	function Perbuatan(){
		parent::MY_Controller();
		$this->validate_cookie();
	}
	
	function index(){
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('departemen_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array('view'=>'template/horz_nav', 
			'view_data'=>array('data'=>$CONF['nav']['psdm']));
		$layoutConf['right_content'] = array('view'=>'perbuatan/psdm/overview', 
			'view_data'=>array(
				'limit' => $CONF['search']['limit']
			));
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript_default'][] = 'psdm/perbuatan';
		$pageConf['jscript'] = $pageConf['jscript_default'];
		$pageConf['css'] = $pageConf['css_default'];
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _search(){
		$this->load->library('session');
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->select_last_entry($keysss, false, $limit, $offset, $orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/psdm/table_content', 	array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrname'=>$this->session->userdata('usrname')
			), true); 	
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}
	
	function add(){
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('kota_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array('view'=>'template/horz_nav', 
											'view_data'=>array('data'=>$CONF['nav']['psdm']));
		$layoutConf['right_content'] = array(
			'view'=>'perbuatan/psdm/add', 
			'view_data'=>array(
				'kota_options'=> $this->kota_model->select_all(array('kota_nama'=>'asc')),
			)
		);
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript'] = array_merge(
			$pageConf['jscript_default'],
			array('psdm/perbuatan_add','datepicker','Swiff.Uploader','Fx.ProgressBar', 'FancyUpload',
				'utils/searchDialog'));
		
		$pageConf['css'] = array_merge($pageConf['css_default'], array('datepicker','FancyUpload'));
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _save(){
		$inp = $this->input->post('inp');
		$res = true;
		
		//save pelapor
		if ($inp[0][0]==""){
			$this->load->model('pelapor_model');
			$res &= $this->pelapor_model->insert( array(
	//			'lapor_id'=> $inp[],
				'lapor_nik'=> '',
				'lapor_nama'=> $inp[0][1]
			));
			if (!$res) { 
				echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_model->pelapor_alamat_model(mysql_errno())) );
				return;
			}
			$pelaporID = $this->pelapor_model->get_last_id();
			
			$this->load->model(array('pelapor_alamat_model','kota_model'));
			for($i=0; $i<count($inp[1]); $i+=2){
				$kota_data = $this->kota_model->select_last_entry(false, "kota_id='".$inp[1][$i+1]."'");
				$kota_data = (array)$kota_data->row();
				
				$res &= $this->pelapor_alamat_model->insert( array(
	//				'lapor_alm_id'=> $inp[],	
					'lapor_alm_alamat'=> $inp[1][$i],	
					'lapor_alm_kode_pos'=> $kota_data['kota_kode_pos'],
		        	'lapor_alm_kode_area'=> $kota_data['kota_kode_area_telepon'],
		        	'lapor_alm_kota'=> $kota_data['kota_nama'],
		        	'lapor_alm_propinsi'=> $kota_data['propinsi_nama'],
		        	'lapor_id'=> $pelaporID
				));
				
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_alamat_model->pelapor_alamat_model(mysql_errno())) );
					return;
				}
			}
			
			$this->load->model('pelapor_telepon_model');
			for($i=0; $i<count($inp[2]); $i+=2){
				$res &= $this->pelapor_telepon_model->insert( array(
					'lapor_tlp_no'=> $inp[2][$i]."-".$inp[2][$i+1],
					'lapor_id'=> $pelaporID
				));
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_telepon_model->pelapor_alamat_model(mysql_errno())) );
					return;
				}
			}
		}
		else{
			$pelaporID = $inp[0][0];
		}
		
		//save perbuatan
		$this->load->model('perbuatan_model');
		$this->load->library('session');
    	
		$res &= $this->perbuatan_model->insert( array(
//			'perb_id'=> $inp[],
			'perb_tgl_lapor'=> $inp[3],
			'perb_tempat_kejadian'=> $inp[5],
			'perb_tgl_kejadian'=> $inp[4],
			'perb_keterangan'=> $inp[8],
			'perb_status'=> 'DR',
			'perb_status_change'=> date("Y-m-d H:i:s", time()),
			'lapor_id'=> $pelaporID,
			'perb_poster'=> md5($this->session->userdata('usrname'))
		));
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		$perbuatanID = $this->perbuatan_model->get_last_id();
		
		$this->load->model('perbuatan_detil_model');
		for($i=0; $i<count($inp[7]); $i+=2){
			$res &= $this->perbuatan_detil_model->insert(array(
				'perb_id'=> $perbuatanID,
				'kary_id'=> $inp[7][$i],
				'kary_jbt_id'=> $inp[7][$i+1],
				'detachiev_id'=> $inp[6],
			
				//@NOTE : saat ini diisi dengan nol, update saat approve
				'deperb_point'=> 0,
				'deperb_count'=> 0
			));
		}
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_detil_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//save the uploaded file to the database
		$this->load->model('perbuatan_bukti_model');
		$fields = array('perb_dok_file_size','perb_dok_file_name','perb_dok_file_type','perb_dok_content','perb_id');
		foreach($inp[9] as $ff){
			$path = "system/cache/$ff";
			$value = array();
			$fileSize =  filesize ($path);
			
			$value[] = $fileSize;
			$value[] = addslashes(preg_replace('/(.*)\[/i','', str_replace(']','',$ff)));
			
			$info = @getimagesize($path);
			$value[] = $info['mime'];
			$value[]  = fread( fopen($path, "r"), $fileSize ); 
			$value[] = $perbuatanID;
			
			$res &= $this->perbuatan_bukti_model->insert(array_combine($fields, $value));
			
			//delete file
			@unlink($path);
		}
		
		echo json_encode(array('error'=>!$res,'msg'=>"Proses simpan selesai",'location'=>site_url(array('psdm','perbuatan'))));
	}
	
	function _delete($id){
		$this->load->model(array('perbuatan_model','perbuatan_detil_model','perbuatan_bukti_model'));
		$res = $this->perbuatan_bukti_model->delete(array('perb_id' => $id));
		$res &= $this->perbuatan_detil_model->delete(array('perb_id' => $id));
		$res &= $this->perbuatan_model->delete(array('perb_id' => $id));
		$msg = $res? "Proses hapus selesai" : "Proses hapus gagal, ".$this->perbuatan_model->mysql_innodb_error(mysql_errno());
		echo json_encode(array('error'=>!$res,'msg'=>$msg));
	}
	
	function edit($id){
		//load the perbuatan data
		$this->load->model(array('perbuatan_model','perbuatan_detil_model',
			'perbuatan_bukti_model','pelapor_model', 'karyawan_model', 'karyawan_history_jabatan_model'));
		$data = array();
		$perbData = (array) $this->perbuatan_model->select_by_id($id)->row();
		$buktiperbData = $this->perbuatan_bukti_model->select_by_perbuatan($perbData['perb_id']);
		$deperbData = $this->perbuatan_detil_model->select_by_perbuatan($perbData['perb_id']);
		$laporData = (array)$this->pelapor_model->select_by_id($perbData['lapor_id'])->row();
		
		//insert to variable
		$data['perbData'] = $perbData;
		$data['laporData'] = $laporData;
		foreach($deperbData->result_array() as $res){
			$data['deperbData'][] = $res;
		}
		foreach($buktiperbData->result_array() as $res){
			$data['buktiperbData'][] = $res;
		}
		
		//layout the view
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('kota_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array('view'=>'template/horz_nav', 
			'view_data'=>array('data'=>$CONF['nav']['psdm']));
		$layoutConf['right_content'] = array(
			'view'=>'perbuatan/psdm/edit', 
			'view_data'=>array_merge(array(
				'kota_options'=> $this->kota_model->select_all(array('kota_nama'=>'asc')),
				'jenis_options'=>$CONF['achievement']['jenis_options'],
				'tingkat_options'=>array_merge(
					$CONF['detachievement']['tingkat_options']['PE'],
					$CONF['detachievement']['tingkat_options']['PR'])
			),$data)
		);
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript'] = array_merge(
			$pageConf['jscript_default'],
			array('psdm/perbuatan_edit','datepicker','Swiff.Uploader','Fx.ProgressBar', 'FancyUpload',
				'utils/searchDialog'));
		
		$pageConf['css'] = array_merge($pageConf['css_default'], array('datepicker','FancyUpload'));
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _update(){
		$inp = $this->input->post('inp');
		$perbuatanID = $this->input->post('perb_id');
		$res = true;
		
		//save pelapor
		if ($inp[0][0]==""){
			$this->load->model('pelapor_model');
			$res &= $this->pelapor_model->insert( array(
	//			'lapor_id'=> $inp[],
				'lapor_nik'=> '',
				'lapor_nama'=> $inp[0][1]
			));
			if (!$res) { 
				echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_model->pelapor_alamat_model(mysql_errno())) );
				return;
			}
			$pelaporID = $this->pelapor_model->get_last_id();
			
			$this->load->model(array('pelapor_alamat_model','kota_model'));
			for($i=0; $i<count($inp[1]); $i+=2){
				$kota_data = $this->kota_model->select_last_entry(false, "kota_id='".$inp[1][$i+1]."'");
				$kota_data = (array)$kota_data->row();
				
				$res &= $this->pelapor_alamat_model->insert( array(
	//				'lapor_alm_id'=> $inp[],	
					'lapor_alm_alamat'=> $inp[1][$i],	
					'lapor_alm_kode_pos'=> $kota_data['kota_kode_pos'],
		        	'lapor_alm_kode_area'=> $kota_data['kota_kode_area_telepon'],
		        	'lapor_alm_kota'=> $kota_data['kota_nama'],
		        	'lapor_alm_propinsi'=> $kota_data['propinsi_nama'],
		        	'lapor_id'=> $pelaporID
				));
				
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_alamat_model->pelapor_alamat_model(mysql_errno())) );
					return;
				}
			}
			
			$this->load->model('pelapor_telepon_model');
			for($i=0; $i<count($inp[2]); $i+=2){
				$res &= $this->pelapor_telepon_model->insert( array(
					'lapor_tlp_no'=> $inp[2][$i]."-".$inp[2][$i+1],
					'lapor_id'=> $pelaporID
				));
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_telepon_model->pelapor_alamat_model(mysql_errno())) );
					return;
				}
			}
		}
		else{
			$pelaporID = $inp[0][0];
		}
		
		//save perbuatan
		$this->load->model('perbuatan_model');
		$this->load->library('session');
    	
		$res &= $this->perbuatan_model->update(array('perb_id'=>$perbuatanID), array(
//			'perb_id'=> $inp[],
			'perb_tgl_lapor'=> $inp[3],
			'perb_tempat_kejadian'=> $inp[5],
			'perb_tgl_kejadian'=> $inp[4],
			'perb_keterangan'=> $inp[8],
			'perb_status'=> 'DR',
			'perb_status_change'=> date("Y-m-d H:i:s", time()),
			'lapor_id'=> $pelaporID,
			'perb_poster'=> md5($this->session->userdata('usrname'))
		));
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//insert pelaku baru
		$in_array = '';
		$this->load->model('perbuatan_detil_model');
		for($i=0; $i<count($inp[7]); $i+=2){
			$opt = array('insert','update');
			$ind = $this->perbuatan_detil_model->is_exist($perbuatanID, $inp[7][$i])? 1 : 0;
			$res &= $this->perbuatan_detil_model->{$opt[$ind]}(
				array(
					'perb_id'=>$perbuatanID,
					'kary_id'=>$inp[7][$i]),
				array(
					'perb_id'=> $perbuatanID,
					//'kary_id'=> $inp[7][$i],
					'kary_jbt_id'=> $inp[7][$i+1],
					'detachiev_id'=> $inp[6],
				
					//@NOTE : saat ini diisi dengan nol, update saat approve
					'deperb_point'=> 0,
					'deperb_count'=> 0
			));
			$in_array = ($in_array? ',':'')."'".$inp[7][$i]."'";
		}
		//delete that not in array
		$this->perbuatan_detil_model->delete("perb_id='$perbuatanID' AND kary_id NOT IN ($in_array)");
		
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_detil_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//delete uploaded file that not checked
		$this->load->model('perbuatan_bukti_model');
		$uploaded = false;
		foreach($inp['uploaded'] as $up){
			$uploaded .= ($uploaded? ",":"")."'$up'";
		}
		$res &= $this->perbuatan_bukti_model->delete("perb_id = '$perbuatanID' AND perb_dok_id NOT IN ($uploaded)");
		
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_bukti_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//save the uploaded file to the database
		if (isset($inp[9])){
			$fields = array('perb_dok_file_size','perb_dok_file_name','perb_dok_file_type','perb_dok_content','perb_id');
			foreach($inp[9] as $ff){
				$path = "system/cache/$ff";
				$value = array();
				$fileSize =  filesize ($path);
				
				$value[] = $fileSize;
				$value[] = addslashes(preg_replace('/(.*)\[/i','', str_replace(']','',$ff)));
				
				$info = @getimagesize($path);
				$value[] = $info['mime'];
				$value[]  = fread( fopen($path, "r"), $fileSize ); 
				$value[] = $perbuatanID;
				
				$res &= $this->perbuatan_bukti_model->insert(array_combine($fields, $value));
				
				//delete file
				@unlink($path);
			}
		}
		echo json_encode(array('error'=>!$res,'msg'=>"Proses simpan selesai",'location'=>site_url(array('psdm','perbuatan'))));
	}
	
	function _updateStatus($id, $status){
		$this->load->model('perbuatan_model');
		$this->perbuatan_model->update(array('perb_id'=>$id),  array(
			'perb_status' => $status, 
			'perb_status_change'=>date("Y-m-d H:i:s",time())));
	}
	
	/*********************************
	 * misc
	 *********************************/
	
	function _getJabatanCombo($kary_id){
		$this->load->model('karyawan_history_jabatan_model');
		$rest = $this->karyawan_history_jabatan_model->getActive($kary_id);
		$cc = "";
		foreach($rest->result_array() as $row){
			$cc .= "<option value='". $row['kary_jbt_id'] ."'>". $row['jbt_nama']." [".$row['dep_nama']."]" ."</option>";
		}
		$this->finalize_view_str($cc);
	}
	
	function _loadImage($image){
		$this->load->model('perbuatan_bukti_model');
		$img = (array)$this->perbuatan_bukti_model->select_by_id($image)->row();
		header("Content-type: ".$img['perb_dok_file_type']);
		print $img['perb_dok_content'];
	}
}
/* End of file users/perbuatan.php */
/* Location: ./system/application/controllers/users/perbuatan.php */